//
//  HelloWorldLayer.m
//  Maze
//
//  Created by Lin Tian on 9/9/11.
//  Copyright tina 2011. All rights reserved.
//


// Import the interfaces
#import "HelloWorldLayer.h"
#import "Hud.h"
#import "Joystick.h"
#import "Player.h"

// HelloWorldLayer implementation
@implementation HelloWorldLayer

@synthesize tileMap=_tileMap;
@synthesize background=_background;
@synthesize meta=_meta;
@synthesize player=_player;
@synthesize foreground=_foreground;
@synthesize room = _room;
@synthesize remotePlayerList;
@synthesize itemPool;

+(CCScene *) sceneWithGame:(HelloWorldLayer *)game
{
	// 'scene' is an autorelease object.
	CCScene *scene = [CCScene node];
	
	// add layer as a child to scene
	[scene addChild: game z:1 tag:GamePage];
    
    Hud *gameHud = [[Hud alloc] initWithPlayer:game.player];
    [scene addChild:gameHud z:2 tag:HudTag];
	
	// return the scene
	return scene;
}

+(CCScene*)scene
{
    // 'scene' is an autorelease object.
	CCScene *scene = [CCScene node];
    
    Joystick* control = [Joystick node];
    [scene addChild:control z:3 tag:TOUCHLAYER];
	
    HelloWorldLayer* game = [HelloWorldLayer node];
    
	// add layer as a child to scene
	[scene addChild: game z:1 tag:GamePage];
    
    control.player = game.player;
    
    Hud *gameHud = [[Hud alloc] initWithPlayer:game.player];
    [scene addChild:gameHud z:2 tag:HudTag];
	
	// return the scene
	return scene;
}

// on "init" you need to initialize your instance
-(id) init
{
	// always call "super" init
	// Apple recommends to re-assign "self" with the "super" return value
	if( (self=[super init])) {
        
        //init basic stuff
        self.remotePlayerList = [NSMutableArray array];
        self.itemPool = [NSMutableArray array];

		/*************************************  init tile map  ***************************/
		self.tileMap = [CCTMXTiledMap tiledMapWithTMXFile:@"tilemap.tmx"];
        self.background = [_tileMap layerNamed:@"background"];
		
		// add the label as a child to this Layer
		[self addChild: _tileMap z:-1];
        
        //init meta data for map used for collision
        self.meta = [_tileMap layerNamed:@"meta"];
        self.meta.visible = NO;
        
        self.foreground = [_tileMap layerNamed:@"foreground"];
        
        /*CCTMXObjectGroup *objects = [_tileMap objectGroupNamed:@"objects"];
        NSAssert(objects != nil, @"'Objects' object group not found");
        NSMutableDictionary *spawnPoint = [objects objectNamed:@"SpawnPoint"];        
        NSAssert(spawnPoint != nil, @"SpawnPoint object not found");
        int x = [[spawnPoint valueForKey:@"x"] intValue];
        int y = [[spawnPoint valueForKey:@"y"] intValue];
        
        self.player = [LocalPlayer player];
        [self.player initSpriteWithParentNode:self position:ccp(x,y)];*/
        
		//set up the camera
        [self setViewpointCenter:self.player.position];
        
        //add item to itempool
        /*Item* anItem = [[Item alloc] init];
        [self.itemPool addObject:anItem];
        [anItem initSpriteWithParentNode:self inPosition:CGPointMake(50, 3000)];
        anItem.sprite.visible = NO;
        
        anItem = [[Item alloc] init];
        [self.itemPool addObject:anItem];
        [anItem initSpriteWithParentNode:self inPosition:CGPointMake(200, 2960)];
        anItem.sprite.visible = NO;*/
        //[anItem release];
		
		//set up game update
        [self schedule:@selector(gameUpdate:) interval:0.1];
	}
	return self;
}

-(void)gameUpdate:(ccTime)dt
{
    //deal with collision, move player
    if (_player.position.x <= (_tileMap.mapSize.width*_tileMap.tileSize.width)&&
        _player.position.y <= (_tileMap.mapSize.height*_tileMap.tileSize.height)&&
        _player.position.x >=0 && _player.position.y >= 0) {
        [self setPlayerPosition:ccpAdd(_player.position, _player.speed)];
    }
    [self setViewpointCenter:_player.position];
    
    //update view of character
    CGPoint loc;
    float angle;
    CCSprite* anItem=nil;
    for (int i = 0; i<[itemPool count]; i++) {
        anItem = ((Item*)[itemPool objectAtIndex:i]).sprite;
        loc = anItem.position;
        loc = ccpSub(loc, self.player.position);
        if (ccpLength(loc)>self.player.viewRadius) {
            anItem.visible = NO;
            continue;
        }else{
            angle = ccpAngle(loc, self.player.viewDirection)*(180.0/M_PI);
            if (angle<self.player.viewPort) {
                anItem.visible = YES;
            }else
            {
                anItem.visible = NO;
            }
        }
    }
}
         


-(void)setViewpointCenter:(CGPoint)position {
    CGSize winSize = [[CCDirector sharedDirector] winSize];
    
    int x = MAX(position.x, winSize.width/2);
    int y = MAX(position.y, winSize.height/2);
    
    x = MIN(x, (_tileMap.mapSize.width * _tileMap.tileSize.width) - winSize.width/2);
    y = MIN(y, (_tileMap.mapSize.height * _tileMap.tileSize.height) - winSize.height/2);
    
    CGPoint actualPosition = ccp(x,y);
    
    CGPoint centerOfView = ccp(winSize.width/2, winSize.height/2);
    CGPoint viewPoint = ccpSub(centerOfView, actualPosition);
    self.position = viewPoint;
}

-(CGPoint)tileCoordForPosition:(CGPoint)position
{
    int x = position.x / self.tileMap.tileSize.width;
    int y = ((self.tileMap.mapSize.height * self.tileMap.tileSize.height) - position.y)/self.tileMap.tileSize.height;
    return ccp(x,y);
}

-(void)setPlayerPosition:(CGPoint)position{
    CGPoint tileCoord = [self tileCoordForPosition:position];
    int tileGid = [self.meta tileGIDAt:tileCoord];
    if (tileGid) {
        NSDictionary *properties = [self.tileMap propertiesForGID:tileGid];
        if (properties) {
            NSString *collision = [properties valueForKey:@"collidable"];
            if (collision && [collision compare:@"yes"] == NSOrderedSame) {
                return;
            }
        }
    }
    
    if (tileGid) {
        NSDictionary *properties = [self.tileMap propertiesForGID:tileGid];
        if (properties) {
            NSString *collectable = [properties valueForKey:@"collectable"];
            NSString *type =[properties valueForKey:@"type"];
            if (collectable && [collectable compare:@"yes"] == NSOrderedSame) {
                Item* anItem;
                if (type && [type compare:@"0"] == NSOrderedSame) {
                    anItem = [[SpeedUp alloc] init];
                }else if(type && [type compare:@"1"] == NSOrderedSame)
                {
                    anItem = [[Invisible alloc] init];
                }
                if([self.player pickupItem:anItem])
                {
                    [self.meta removeTileAt:tileCoord];
                    [self.foreground removeTileAt:tileCoord];
                }
                //[anItem release];
            }
        }
    }
    self.player.position = position;
}

// on "dealloc" you need to release all your retained objects
- (void) dealloc
{
	// in case you have something to dealloc, do it in this method
	// in this particular example nothing needs to be released.
	// cocos2d will automatically release all the children (Label)
    
    self.tileMap = nil;
    self.background = nil;
    self.player = nil;
    self.meta = nil;
    self.foreground = nil;
	//self.parser = nil;
	
	// don't forget to call "super dealloc"
	[super dealloc];
}
@end
